package com.company.cloud.work.modules.mgr.controller;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;

import com.company.cloud.common.auth.annotation.StaffLogc;
import com.company.cloud.common.bean.BaseClientResult;
import com.company.common.server.constant.IRelBusiType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.auth.annotation.Authc;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant.EnabledEnum;
import com.company.cloud.common.constant.BaseConstant.YNEnum;
import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.common.utils.StrSplitUtils;
import com.company.cloud.user.modules.api.response.UserSimple;
import com.company.cloud.user.modules.api.service.UserRemoteService;
import com.company.cloud.work.modules.base.entity.SaleRecordInfo;
import com.company.cloud.work.modules.base.service.SaleRecordInfoService;
import com.company.cloud.work.modules.cache.models.WorkSaleLogModel;
import com.company.cloud.work.modules.cache.utils.CrmWorkChangeUtils;
import com.company.cloud.work.modules.mgr.controller.req.WorkSaleLogQuery4PageParam;
import com.company.cloud.work.modules.mgr.controller.req.WorkSaleLogSaveParam;
import com.company.cloud.work.modules.mgr.controller.req.WorkSaleLogUpdateParam;
import com.company.cloud.work.modules.mgr.service.WorkReceiptMgrService;

import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Authc
@RestController
@RequestMapping("/mgr/crm/workSaleLog")
@Api(tags = "CRM_Mgr_销售日志")
public class WorkSaleLogMgrController {

	
	@Autowired
	private SaleRecordInfoService saleRecordInfoService;
	@Autowired
	private UserRemoteService userRemoteService;
	@Autowired
	private WorkReceiptMgrService workReceiptMgrService;

	@PostMapping("/query")
	@ApiOperation(value = "查询", response = WorkSaleLogModel.class)
	public BaseResult query(@RequestBody WorkSaleLogQuery4PageParam params) {
		LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
		String sendUserId = null;
		if (CheckUtils.hasInt(params.getSendUserId())) {
			sendUserId = StrUtil.format(",{},", params.getSendUserId());
		}
		IPage<SaleRecordInfo> page = saleRecordInfoService.page(new Page<>(params.getPage(), params.getRows()),
				new QueryWrapper<SaleRecordInfo>().eq("rows_state", EnabledEnum.ENABLED.getCode())
						.eq("company_no", userInfo.getCompanyNo())
						.eq(CheckUtils.hasInt(params.getUserId()), "user_id", params.getUserId())
						.eq(StringUtils.hasText(params.getRelBizType()), "rel_biz_type", params.getRelBizType())
						.eq(StringUtils.hasText(params.getRelBizId()), "rel_biz_id", params.getRelBizId())
						.like(StringUtils.hasText(sendUserId), "send_user_ids", sendUserId));
		
		if (page == null || CollectionUtils.isEmpty(page.getRecords())) {
			return BaseResult.ok();
		}
		Set<Integer> userIds = new HashSet<Integer>();
		page.getRecords().forEach(item -> {
			if (CheckUtils.hasInt(item.getUserId())) {
				userIds.add(item.getUserId());
			}
			userIds.addAll(StrSplitUtils.parse2set(item.getSendUserIds(), Integer.class));
		});

		BaseClientResult<Map<Integer, UserSimple>> userMapResult = userRemoteService.getUserMapByIds(userIds);
		Map<Integer, UserSimple> userMap=BaseClientResult.getResultData(userMapResult,new HashMap<>());
		IPage<WorkSaleLogModel> data = page.convert(new Function<SaleRecordInfo, WorkSaleLogModel>() {
			@Override
			public WorkSaleLogModel apply(SaleRecordInfo entity) {
				return CrmWorkChangeUtils.getWorkSaleLogModel(entity, userMap);
			}
		});

		return BaseResult.ok(data);
	}

	@PostMapping("/add")
	@ApiOperation(value = "新增", response = BaseResult.class)
	@StaffLogc(title = "新增销售", action = "新增销售", actionAdo = "销售")
	public BaseResult add(@RequestBody WorkSaleLogSaveParam params) {
		ValidatorUtils.validate(params);
		LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
		SaleRecordInfo entity = new SaleRecordInfo();
		entity.setCompanyNo(userInfo.getCompanyNo());
		entity.setUserId(userInfo.getId());
		entity.setType(params.getType());
		entity.setContent(params.getContent());
		entity.setRelBizType(params.getRelBizType());
		entity.setRelBizId(params.getRelBizId());
		entity.setSendUserIds(StrSplitUtils.list2string_prefix(params.getSendUserIds()));
		entity.addCreateParam(userInfo);
		entity.addEditParam(userInfo);
		saleRecordInfoService.save(entity);
		return BaseResult.ok();
	}

	@PostMapping("/edit")
	@ApiOperation(value = "修改", response = BaseResult.class)
	@StaffLogc(title = "修改销售", action = "修改销售", actionAdo = "销售")
	public BaseResult edit(@RequestBody WorkSaleLogUpdateParam params) {
		ValidatorUtils.validate(params);
		SaleRecordInfo entity = saleRecordInfoService.getById(params.getId());
		if (entity == null || EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}
		LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
		entity.setType(params.getType());
		entity.setContent(params.getContent());
		entity.setSendUserIds(StrSplitUtils.list2string_prefix(params.getSendUserIds()));
		entity.addEditParam(userInfo);
		saleRecordInfoService.updateById(entity);
		return BaseResult.ok();
	}

	@GetMapping("/get")
	@ApiOperation(value = "获取", response = WorkSaleLogModel.class)
	public BaseResult get(@RequestParam("id") Integer id) {
		SaleRecordInfo entity = saleRecordInfoService.getById(id);
		if (entity == null || EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}
		LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
		Set<Integer> userIds = new HashSet<Integer>();
		userIds.add(entity.getUserId());
		BaseClientResult<Map<Integer, UserSimple>> userMapResult = userRemoteService.getUserMapByIds(userIds);
		
		WorkSaleLogModel data = CrmWorkChangeUtils.getWorkSaleLogModel(entity, BaseClientResult.getResultData(userMapResult,new HashMap<>()));
		if (YNEnum.YES.getCode().equals(entity.getIsReceipt())) {
			workReceiptMgrService.save(IRelBusiType.CRM_Sale_Log_ID, entity.getId().toString(), null, userInfo);
		}
		return BaseResult.ok(data);
	}

	@GetMapping("/remove")
	@ApiOperation(value = "删除", response = BaseResult.class)
	@StaffLogc(title = "删除销售", action = "删除销售", actionAdo = "销售")
	public BaseResult remove(@RequestParam("id") Integer id) {
		SaleRecordInfo entity = saleRecordInfoService.getById(id);
		if (entity == null || EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}
		LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
		entity.setRowsState(EnabledEnum.DISABLED.getCode());
		entity.addEditParam(userInfo);
		saleRecordInfoService.updateById(entity);
		return BaseResult.ok();
	}

}
